//
//  JXWorkUploadViewController.m
//  JXAddressApp
//
//  Created by zhhw_home on 2018/10/28.
//  Copyright © 2018年 zhhw_home. All rights reserved.
//

#import "JXWorkUploadViewController.h"
#import "EgovaNetworking.h"
#import "QMUITips.h"

@interface JXWorkUploadViewController ()

@end

@implementation JXWorkUploadViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self){
        [self initializeForm];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self){
        [self initializeForm];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"作品上传";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(save:)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [self initializeForm];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)initializeForm
{
    XLFormSectionDescriptor * section;
    XLFormRowDescriptor * row;
    
    XLFormDescriptor *form = [XLFormDescriptor formDescriptorWithTitle:@"Add Event"];
    
    // First section
    section = [XLFormSectionDescriptor formSection];
    [form addFormSection:section];
    
    // Title
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"username" rowType:XLFormRowDescriptorTypeName title:@"真实姓名:"];
    row.required = YES;
    row.requireMsg = @"姓名不能为空";
    [row.cellConfigAtConfigure setObject:@"您的姓名" forKey:@"textField.placeholder"];
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"userphone" rowType:XLFormRowDescriptorTypePhone title:@"联系电话:"];
    row.required = YES;
    row.requireMsg = @"电话不能为空";
    [row.cellConfigAtConfigure setObject:@"您的联系电话" forKey:@"textField.placeholder"];
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"useremail" rowType:XLFormRowDescriptorTypeEmail title:@"电子邮箱:"];
    row.required = YES;
    row.requireMsg = @"邮箱不能为空";
    [row.cellConfigAtConfigure setObject:@"您的电子邮箱" forKey:@"textField.placeholder"];
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"solicittitle" rowType:XLFormRowDescriptorTypeTextView title:@"作品标题:"];
    row.required = YES;
    row.requireMsg = @"作品标题不能为空";
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"solicitsubtitle" rowType:XLFormRowDescriptorTypeTextView title:@"文字介绍:"];
    row.required = YES;
    row.requireMsg = @"文字介绍不能为空";
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"uploadfile" rowType:XLFormRowDescriptorTypeImage title:@"选择图片:"];
    row.height = 100.f;
    [section addFormRow:row];
 
    
    self.form = form;
}

- (void)save:(id)sender
{
    NSArray *errors = [self.form localValidationErrors:self];
    if (errors.count > 0) {
        NSError *error = [errors firstObject];
        
        [QMUITips showWithText:error.userInfo[NSLocalizedDescriptionKey] inView:self.view hideAfterDelay:1.5f];
        return;
    }
    
    NSDictionary *forms = [self.form formValues];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:forms];
    [params setObject:[[self class] uuidString] forKey:@"uploadname"];
    [params setObject:[[self class] dateString] forKey:@"publishtime"];
    
    UIImage *image = params[@"uploadfile"];
    params[@"uploadfile"] = nil;
    if (image == nil) {
        [QMUITips showWithText:@"图片不能为空" inView:self.view hideAfterDelay:1.5f];
        return;
    }
    
    [QMUITips showLoading:@"提交中，请稍候..." inView:self.view];
    
    [EgovaNetworking uploadWithImage:image
                                 url:@"http://wegis.net/demo/home/baseinfo/solicitarticle"
                            filename:params[@"uploadname"]
                                name:@"uploadfile"
                            mimeType:@"image/jpeg"
                          parameters:params
                            progress:nil
                           completed:^(NSInteger code, id data, NSString *msg) {
                               [QMUITips hideAllTipsInView:self.view];
                               if (code == 0) {
                                   [self performSelector:@selector(dismissVC) withObject:nil afterDelay:0.25];
                               }
                               else {
                                   [QMUITips showInfo:@"上传失败，请稍候重试！"];
                               }
                          }];
}

- (void)dismissVC
{
    [self.navigationController popViewControllerAnimated:YES];
}

+ (NSString *)uuidString
{
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    NSString *uuid = [NSString stringWithString:(__bridge NSString *)uuid_string_ref];
    CFRelease(uuid_ref);
    CFRelease(uuid_string_ref);
    return [uuid lowercaseString];
}

+ (NSString *)dateString
{
    NSDate *currentDate = [NSDate date];
    //用于格式化NSDate对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设置格式：zzz表示时区
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
    //NSDate转NSString
    NSString *currentDateString = [dateFormatter stringFromDate:currentDate];
    
    return currentDateString;
}


@end
